<template>
    <div class="order-list">
      <scroller lock-x ref="scrollerBottom" @on-scroll="onScroll" v-if="orderList.length > 0">
        <div class="order-list-container">
            <div class="pro-cont" v-for="item in orderList">
            <div class="pro-title">
                <span class="c-tit">
                  &nbsp;
                  <!--{{ item.storeName }}-->
                </span>
                <a class="btn-delhis" href="javascript:;" @click="delOrder(item.orderId)" v-if="item.statusDesc=='已取消'"></a>
                <span class="c-peo">{{ showStatusDesc(item.status, item.isPickUp) }}</span>
            </div>
            <a :href="'/#/orderDetail/' + item.orderId">
                <div class="pro-detail" :class="{'pro-more': item.orderItems.length > 1}">
                <div class="o-index-pro-pic">
                    <template v-for="(product, i) in item.orderItems">
                    <img alt="" :src="product.commdtyCode | newImgUrl(product.imgFlag)" @error.once="imgError" v-if="i < 4">
                    <!--<img alt="" :src="getImgPath(product)" @error.once="imgError" v-if="i < 4">-->
                    </template>
                    <i class="more-icon" v-if="item.orderItems.length > 4"></i>
                </div>
                <div class="qa-price clearfix" v-if="item.orderItems.length > 1">

                </div>
                <template v-else>
                    <div class="o-pro-info">{{ item.orderItems[0].commdtyName }}</div>
                    <div class="qa-price clearfix">
                    <span class="price-text">
                        <span class="goods-price">&yen;{{ item.orderItems[0].price }}</span>
                        <span class="o-pro-num">&times;{{ item.orderItems[0].quantity }}</span>
                    </span>
                    </div>
                </template>
                </div>
            </a>
            <div class="qa-price clearfix">
                <span class="qrcode qrcode-fl" @click="qrcodeAlert(item.orderId)"></span>
                <span v-if="item.orderItems.length > 1">共{{ item.totalCount }}件商品</span>
                <span class="pay-price">实付：&yen;{{ item.payAmt }}</span>
            </div>
            <!-- 底部状态按钮 -->
            <div class="qa-btn" v-if="(['00', '02' ,'03', '04', '05', '06'].indexOf(item.status) >= 0 && item.isPickUp == 0) || (item.status == '00' && item.isPickUp == 1)">
                <!-- 联系微仓主 -->
                <!-- 联系快递员 -->
                <a class="btn-go-pay btn" :href="'/#/cart3/' + item.orderId+'?from=orderlist'"
                v-if="item.status == '00'"
                >去支付</a>
                <template v-if="item.isPickUp == 0">
                <a class="btn-gray btn"
                v-if="item.status == '06'" href="javascript:;" @click="cuidan_xiaoge(item.courierTel)"
                >催单</a>
                <a class="btn-gray btn" href="javascript:;" @click="cuidan(item.wcOwnerTel)"
                v-if="item.status == '02' || item.status == '03' || item.status == '04' || item.status == '05'"
                >催单</a>
                </template>
            </div>
            </div>
            <load-more :tip="'正在加载'" v-if="pageNumber <= totalPage"></load-more>
            <load-more :show-loading="false" :tip="'已经到最底了哦~'" background-color="#FBF9FE"></load-more>
        </div>
        </scroller>

        <div class="empty" v-else>
            <i></i>
            <p>你还没有提交过订单～</p>
        </div>
        <toast v-model="toastDataFailed" type="text" position="middle" width="10rem">数据加载失败</toast>

      <div class="alertCode-container" v-show="alertCode">
        <div class="code-bg">
          <div id="qrcode"></div>
          <i @click="alertCode=false"></i>
          <span></span>
        </div>
        </div>

    </div>
</template>

<script>
import fetch from '../../config/fetch'
import { tps, img } from '../../config/env'
import { Scroller, LoadMore, Toast } from 'vux'
import router from '@/router/index'
import { statusInfo } from './statusInfo'
import QRCode from './QRCode.js'
export default {
  data () {
    return {
      alertCode: false,
      onFetching: false,
      pageNumber: 1,
      orderList: [],
      toastDataFailed: false,
      totalPage: 1
    }
  },
  mounted () {
    this.fetchData()
  },
  created(){
    this.$store.commit('showMask', true)
  },
  methods: {
    qrcodeAlert (orderId) {
        this.alertCode = true ;
      $('#qrcode img').remove();
       new QRCode(document.getElementById("qrcode"), {
          text: orderId,
          width: 200,
          height: 200,
          colorDark : "#000000",
          colorLight : "#ffffff",
          correctLevel : QRCode.CorrectLevel.H
        });
    },
    fetchData () {
      this.onFetching = true;
      fetch({
        url: tps + '/app/orderCenter/queryOrderList.do',
        jsonp: 'callBack',
        params: {
          app: 'wap',
          appVersion: '3.2.2',
          pageNumber: this.pageNumber,
          status: '',
          pageSize: 10
        }
      }).then((res) => {
        this.$store.commit('showMask', false)
        if (res && res.data && res.data.orderList) {
          this.totalPage = parseInt(res.data.totalPage);
          this.orderList = this.orderList.concat( res.data.orderList );

          // 刷新scroller
          this.$nextTick(() => {
            this.$refs.scrollerBottom.reset()
          })

          this.onFetching = false;
          this.pageNumber++;
        }
      }).catch(err => {
        setTimeout(() => {
          this.onFetching = false;
        }, 1000);
        this.toastDataFailed = true;
      })
    },
    onScroll(position) {
      if (this.onFetching || this.pageNumber > this.totalPage) {
        return;
      }
      let conHeight = this.$el.querySelector('.xs-container').scrollHeight;
      if (position.top + document.documentElement.clientHeight > conHeight - 100) {
        this.fetchData();
      }
    },
    getLinkPath (item) {
      return `orderDetail.html?orderId=${ item.orderId }`
    },
    getImgPath (product) {
      return img() + `/uimg/cmws/catentries/${ product.commdtyCode }_1_200x200.jpg`
    },
    getPayPath (item) {
      return `/app/cart/cart3.html?orderid=${ item.orderId }`
    },
    getTrackPath (item) {
      return `orderTracking.html?orderId=${ item.orderId }`
    },
    imgError(event) {
      event.target.src = '/static/images/pro-default.png';
    },

    delOrder(orderid) {
      let that = this;

      AlertBox({
        type: "doubleBtn",
        alertCls: "sn-double-box",
        alertType: "fixed",
        msg: "确认删除此订单吗？",
        confirm: function(){
          fetch({
            type: 'post',
            url: tps + '/app/orderCenter/deleteOrder.do',
            jsonp: 'callBack',
            params: {
              orderId: orderid
            }
          }).then((res) => {
            if (res && res.code == '1') {
              for (let i = 0; i < that.orderList.length; i++) {
                if (that.orderList[i].orderId == orderid) {
                  that.orderList.splice(i, 1);
                }
              }
            }
          });
        }
      });
    },


    cuidan(tel) {
        AlertBox({
            type: "doubleBtn",
            alertType: "fixed",
            msg: "已通知苏鲜生店尽快为您配送，请耐心等待一会儿~",
            confirmText: '我再等等',
            cancelText: '联系苏鲜生',
            cancel: function(){
                location.href = 'tel:' + tel;
            }
        });
    },
    cuidan_xiaoge(tel) {
        AlertBox({
            type: "doubleBtn",
            alertType: "fixed",
            msg: tel,
            confirm: function(){
                location.href = 'tel:' + tel;
            }
        });
    },

    showStatusDesc(code, isPickUp) {
        let str = '';
        $.each(statusInfo[isPickUp == '1' ? 'pickUp' : 'delivery'], function(si, sv){
            if (sv.data.indexOf(code) >= 0) {
                str = sv.name;
            };
        });
        return str;
    }
  },
  components: {
    Scroller,
    LoadMore,
    Toast
  }
}
</script>
<style lang="scss" scoped>
@import "./style";
</style>
